package io.arukas.config;

import io.arukas.filter.HttpBasicAuthorize;
import io.arukas.webservice.HelloServiceImpl;
import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templatemode.TemplateMode;

import javax.xml.ws.Endpoint;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA. <br/>
 *
 * @author 牛玉贤 <br/>
 * @date 08/05/2020 13:52 <br/>
 * @email ncc0706@gmail.com <br/>
 */
@Configuration
public class WebServiceConfig {

    @Autowired
    private Bus bus;

    @Bean
    public Endpoint endpoint() {
        // http://localhost:8000/services/helloworld/sayHello?message=123
        EndpointImpl endpoint = new EndpointImpl(bus, new HelloServiceImpl());
        endpoint.publish("/helloworld");
        return endpoint;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        HttpBasicAuthorize httpBasicFilter = new HttpBasicAuthorize();
        registrationBean.setFilter(httpBasicFilter);
        List<String> urlPatterns = new ArrayList<>();
        urlPatterns.add("/services/*");
        registrationBean.setUrlPatterns(urlPatterns);
        return registrationBean;
    }


    @Bean
    public SpringResourceTemplateResolver xmlTemplateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(new AnnotationConfigApplicationContext());
        resolver.setPrefix("classpath:/xml/");
        resolver.setSuffix(".xml");
        resolver.setCharacterEncoding("UTF-8");
        resolver.setTemplateMode(TemplateMode.XML);
        return resolver;
    }

    @Bean
    public SpringTemplateEngine xmlTemplateEngine(SpringResourceTemplateResolver xmlTemplateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(xmlTemplateResolver);
        return templateEngine;
    }
}
